<template>
    <div class="file-manager-container">
        <div class="header-bar">
            <h2>Java文件管理</h2>
            <div class="header-actions">
                <el-button type="primary" @click="showCreateDialog = true">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    新建文件
                </el-button>
                <el-button @click="loadFileList">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </div>
        </div>

        <!-- 文件列表 -->
        <el-card class="file-list-card" shadow="never">
            <template #header>
                <span>热插拔Java文件</span>
            </template>

            <el-table v-loading="loading" :data="fileList" stripe style="width: 100%" class="fixed-table">
                <el-table-column prop="name" label="文件名" min-width="200" />
                <el-table-column prop="relativePath" label="相对路径" min-width="250" show-overflow-tooltip />
                <el-table-column prop="size" label="大小" width="100">
                    <template #default="{ row }">
                        {{ formatFileSize(row.size) }}
                    </template>
                </el-table-column>
                <el-table-column prop="lastModified" label="修改时间" width="160">
                    <template #default="{ row }">
                        {{ formatDateTime(row.lastModified) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="280" fixed="right">
                    <template #default="{ row }">
                        <el-button-group>
                            <el-button size="small" @click="editFile(row)">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                                编辑
                            </el-button>
                            <el-button size="small" type="success" @click="compileFile(row)"
                                :loading="compilingFiles.includes(row.path)">
                                <el-icon>
                                    <Tools />
                                </el-icon>
                                编译
                            </el-button>
                            <el-button size="small" type="info" @click="useInTask(row)">
                                <el-icon>
                                    <Link />
                                </el-icon>
                                用于任务
                            </el-button>
                            <el-button size="small" type="danger" @click="deleteFile(row)">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                                删除
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 代码编辑器 -->
        <el-card v-if="showEditor" class="editor-card" shadow="never">
            <template #header>
                <div class="editor-header">
                    <span>代码编辑器 - {{ currentFile?.name || '新文件' }}</span>
                    <el-button @click="closeEditor">
                        <el-icon>
                            <Close />
                        </el-icon>
                        关闭
                    </el-button>
                </div>
            </template>

            <CodeEditor ref="codeEditorRef" v-model="editorContent" v-model:file-path="editorFilePath" height="500px"
                @saved="handleFileSaved" @compiled="handleFileCompiled" />
        </el-card>

        <!-- 新建文件对话框 -->
        <el-dialog v-model="showCreateDialog" title="新建Java文件" width="600px">
            <el-form :model="newFileForm" :rules="newFileRules" ref="newFileFormRef" label-width="120px">
                <el-form-item label="类名" prop="className">
                    <el-input v-model="newFileForm.className" placeholder="例: MyCustomTask"
                        @input="updateSuggestedPath" />
                </el-form-item>
                <el-form-item label="包名" prop="packageName">
                    <el-input v-model="newFileForm.packageName" placeholder="例: com.example.tasks"
                        @input="updateSuggestedPath" />
                </el-form-item>
                <el-form-item label="文件路径">
                    <el-input v-model="newFileForm.filePath" placeholder="自动生成的文件路径" readonly />
                </el-form-item>
                <el-form-item label="模板">
                    <el-select v-model="newFileForm.template" placeholder="选择代码模板" style="width: 100%">
                        <el-option label="Hello World 任务" value="helloWorld" />
                        <el-option label="数据处理任务" value="dataProcessing" />
                        <el-option label="系统监控任务" value="systemMonitor" />
                        <el-option label="空白Java类" value="blank" />
                    </el-select>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showCreateDialog = false">取消</el-button>
                    <el-button type="primary" @click="createNewFile" :loading="creating">创建并编辑</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Edit, Tools, Link, Delete, Close } from '@element-plus/icons-vue'
import CodeEditor from '@/components/CodeEditor.vue'
import { fileApi } from '@/api/files'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const fileList = ref([])
const compilingFiles = ref([])
const showEditor = ref(false)
const showCreateDialog = ref(false)
const currentFile = ref(null)
const editorContent = ref('')
const editorFilePath = ref('')

const codeEditorRef = ref()
const newFileFormRef = ref()

// 新建文件表单
const newFileForm = reactive({
    className: '',
    packageName: 'com.example.tasks',
    filePath: '',
    template: 'blank'
})

// 表单验证规则
const newFileRules = {
    className: [
        { required: true, message: '请输入类名', trigger: 'blur' },
        { pattern: /^[A-Z][a-zA-Z0-9]*$/, message: '类名必须以大写字母开头，只能包含字母和数字', trigger: 'blur' }
    ],
    packageName: [
        { required: true, message: '请输入包名', trigger: 'blur' },
        { pattern: /^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)*$/, message: '包名格式不正确', trigger: 'blur' }
    ]
}

// 加载文件列表
const loadFileList = async () => {
    loading.value = true
    try {
        const response = await fileApi.listFiles()
        fileList.value = response.data || []
    } catch (error) {
        console.error('加载文件列表失败:', error)
    } finally {
        loading.value = false
    }
}

// 编辑文件
const editFile = (file) => {
    currentFile.value = file
    editorFilePath.value = file.path
    showEditor.value = true

    // 加载文件内容
    loadFileContent(file.path)
}

// 加载文件内容
const loadFileContent = async (filePath) => {
    try {
        const response = await fileApi.readFile(filePath)
        editorContent.value = response.data.content

        // 设置编辑器内容
        if (codeEditorRef.value) {
            codeEditorRef.value.setValue(response.data.content)
        }
    } catch (error) {
        console.error('加载文件内容失败:', error)
        ElMessage.error('加载文件内容失败')
    }
}

// 编译文件
const compileFile = async (file) => {
    if (compilingFiles.value.includes(file.path)) return

    compilingFiles.value.push(file.path)
    try {
        await fileApi.compileFile(file.path)
        ElMessage.success('编译成功')
    } catch (error) {
        console.error('编译失败:', error)
    } finally {
        compilingFiles.value = compilingFiles.value.filter(path => path !== file.path)
    }
}

// 用于任务
const useInTask = (file) => {
    // 从文件路径提取类名
    const fileName = file.name.replace('.java', '')
    const className = `com.example.tasks.${fileName}`

    // 跳转到任务创建页面，并传递文件信息
    router.push({
        path: '/jobs/create',
        query: {
            targetClass: className,
            javaFilePath: file.path
        }
    })
}

// 删除文件
const deleteFile = async (file) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除文件 "${file.name}" 吗？此操作不可恢复。`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await fileApi.deleteFile(file.path)
        ElMessage.success('文件删除成功')
        await loadFileList()
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除文件失败:', error)
        }
    }
}

// 关闭编辑器
const closeEditor = () => {
    showEditor.value = false
    currentFile.value = null
    editorContent.value = ''
    editorFilePath.value = ''
}

// 更新建议路径
const updateSuggestedPath = async () => {
    if (newFileForm.className && newFileForm.packageName) {
        try {
            const response = await fileApi.suggestPath(newFileForm.className, newFileForm.packageName)
            newFileForm.filePath = response.data.filePath
        } catch (error) {
            console.error('生成路径失败:', error)
        }
    }
}

// 创建新文件
const createNewFile = async () => {
    try {
        const valid = await newFileFormRef.value.validate()
        if (!valid) return

        creating.value = true

        // 生成文件内容
        let content = getTemplateContent(newFileForm.template, newFileForm.className, newFileForm.packageName)

        // 保存文件
        await fileApi.saveFile(newFileForm.filePath, content)

        ElMessage.success('文件创建成功')
        showCreateDialog.value = false

        // 刷新文件列表
        await loadFileList()

        // 打开编辑器
        currentFile.value = {
            name: newFileForm.className + '.java',
            path: newFileForm.filePath
        }
        editorFilePath.value = newFileForm.filePath
        editorContent.value = content
        showEditor.value = true

        // 重置表单
        Object.assign(newFileForm, {
            className: '',
            packageName: 'com.example.tasks',
            filePath: '',
            template: 'blank'
        })

    } catch (error) {
        console.error('创建文件失败:', error)
    } finally {
        creating.value = false
    }
}

// 获取模板内容
const getTemplateContent = (template, className, packageName) => {
    const templates = {
        helloWorld: `package ${packageName};

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * ${className} - Hello World 任务
 */
public class ${className} {
    
    /**
     * 简单的Hello World方法
     */
    public String sayHello() {
        String message = "Hello World! 当前时间: " + 
            LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        System.out.println("[${className}] " + message);
        return message;
    }
}`,

        dataProcessing: `package ${packageName};

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * ${className} - 数据处理任务
 */
public class ${className} {
    
    /**
     * 处理数据方法
     */
    public String processData() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        String message = "数据处理任务执行完成，处理时间: " + timestamp;
        System.out.println("[${className}] " + message);
        return message;
    }
}`,

        systemMonitor: `package ${packageName};

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * ${className} - 系统监控任务
 */
public class ${className} {
    
    /**
     * 系统健康检查
     */
    public String healthCheck() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String result = String.format("[%s] 系统健康检查完成", timestamp);
        System.out.println("[${className}] " + result);
        return result;
    }
}`,

        blank: `package ${packageName};

import java.time.LocalDateTime;

/**
 * ${className} - 自定义任务
 */
public class ${className} {
    
    /**
     * 执行任务方法
     */
    public String execute() {
        String message = "任务执行完成: " + LocalDateTime.now();
        System.out.println("[${className}] " + message);
        return message;
    }
}`
    }

    return templates[template] || templates.blank
}

// 文件保存处理
const handleFileSaved = () => {
    loadFileList() // 刷新文件列表
}

// 文件编译处理
const handleFileCompiled = () => {
    ElMessage.success('文件编译完成')
}

// 格式化文件大小
const formatFileSize = (bytes) => {
    if (!bytes) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期时间
const formatDateTime = (timestamp) => {
    if (!timestamp) return '-'
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN')
}

// 组件挂载
onMounted(() => {
    loadFileList()
})
</script>

<style scoped>
.file-manager-container {
    padding: 0 20px;
    width: 100%;
    box-sizing: border-box;
}

.header-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
    padding: 0 5px;
}

.header-bar h2 {
    margin: 0;
    color: #303133;
}

.header-actions {
    display: flex;
    gap: 10px;
}

.file-list-card,
.editor-card {
    margin-bottom: 15px;
    width: 100%;
}

.file-list-card :deep(.el-card__body),
.editor-card :deep(.el-card__body) {
    padding: 15px;
}

.editor-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.dialog-footer {
    text-align: right;
}

:deep(.el-table) {
    width: 100% !important;
}

/* 表格水平滚动和固定操作列 */
.fixed-table {
    overflow-x: auto;
}

:deep(.fixed-table .el-table__body-wrapper) {
    overflow-x: auto;
}

:deep(.fixed-table .el-table__fixed-right) {
    right: 0 !important;
}

/* 操作按钮不换行 */
:deep(.el-button-group) {
    white-space: nowrap;
    display: inline-flex;
}

:deep(.el-button-group .el-button) {
    flex-shrink: 0;
}

/* 响应式布局 */


@media (max-width: 768px) {
    .file-manager-container {
        padding: 0 10px;
    }

    .header-bar {
        flex-direction: column;
        gap: 15px;
        align-items: flex-start;
    }

    .header-bar h2 {
        font-size: 18px;
    }

    .header-actions {
        width: 100%;
        justify-content: flex-end;
    }

    /* 移动端表格操作按钮优化 */
    :deep(.el-button-group) {
        display: flex !important;
        flex-wrap: wrap !important;
        gap: 4px;
        white-space: normal !important;
    }

    :deep(.el-button-group .el-button) {
        margin: 0;
        font-size: 12px;
        padding: 4px 8px;
        flex-shrink: 1 !important;
    }

    /* 对话框优化 */
    :deep(.el-dialog) {
        width: 95% !important;
        margin: 5vh auto !important;
    }

    :deep(.el-form-item__label) {
        width: 80px !important;
    }
}

@media (max-width: 480px) {
    .file-manager-container {
        padding: 0;
    }

    .header-bar {
        padding: 0;
        margin-bottom: 10px;
    }

    .header-bar h2 {
        font-size: 16px;
    }

    .header-actions .el-button {
        font-size: 12px;
        padding: 6px 12px;
    }

    .header-actions .el-button span {
        display: none;
    }

    .file-list-card :deep(.el-card__body),
    .editor-card :deep(.el-card__body) {
        padding: 10px;
    }

    /* 表格在移动端的优化 */
    :deep(.el-table) {
        font-size: 12px;
    }

    :deep(.el-table .el-table__cell) {
        padding: 6px 4px;
    }

    :deep(.el-table .cell) {
        word-break: break-all;
        line-height: 1.2;
    }

    /* 操作列优化 */
    :deep(.el-button-group) {
        flex-direction: column;
        width: 100%;
    }

    :deep(.el-button-group .el-button) {
        width: 100%;
        margin-bottom: 2px;
        font-size: 11px;
        padding: 3px 6px;
    }

    /* 对话框在移动端优化 */
    :deep(.el-dialog) {
        width: 98% !important;
        margin: 2vh auto !important;
    }

    :deep(.el-form-item) {
        flex-direction: column;
    }

    :deep(.el-form-item__label) {
        width: 100% !important;
        text-align: left !important;
        margin-bottom: 5px;
    }

    :deep(.el-form-item__content) {
        margin-left: 0 !important;
    }

    /* 编辑器在移动端的优化 */
    .editor-card {
        margin-bottom: 10px;
    }

    .editor-header {
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
    }

    .editor-header .el-button {
        align-self: flex-end;
    }
}
</style>